#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Project : chat_model 
# @File    : job_task.py
# @IDE     : PyCharm 
# @Author  :ZH
# @Time    : 2025/1/17 9:29

import time

import redis
import asyncio

from apps import logic
from apps.api.v1.knowledge_api.util import handle_file
from celery_task import celery_app
import json
from tortoise import Tortoise

from core.setting import settings


async def file_handle():
    print('开始执行任务')
    pool = redis.ConnectionPool(host=settings.REDIS_HOST,
                                port=settings.REDIS_PORT,
                                db=settings.REDIS_DEFAULT_DB, decode_responses=True
                                )
    r = redis.Redis(connection_pool=pool)
    task = r.lpop('chat_model:knowledge:file_handle')
    r.close()
    if not task:
        print('当前无任务需要处理')
        return
    # 建立数据库链接
    await Tortoise.init(config=settings.get_orm_base_conf())
    # 将数据序列化
    task_info = json.loads(task)
    file_id = task_info.get('file_id')
    knowledge_id = task_info.get('knowledge_id')
    user_id = task_info.get('user_id')
    # 获取当前的用户信息
    user = await logic.user_logic.get_user_object(user_id=user_id)
    await handle_file(
        file_id=file_id, knowledge_id=knowledge_id, user=user
    )
    await Tortoise.close_connections()


@celery_app.task
def notice():
    # 老版调用方式
    loop = asyncio.get_event_loop()
    loop.run_until_complete(file_handle())


